package org.dromara.assets.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.crypto.digest.DigestUtil;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

@SaIgnore
//@Controller
//@RequestMapping("/markdown/info")
public class InfoController {

    // 定义问题和答案
    private static final String QUESTION = "我爸爸妈妈叫什么名字（通过顿号分隔）？";
    private static final String ANSWER = "a737c4f97dfc996f13af96793fed7de4";

    // 从 JAR 包中读取 Markdown 文件内容
    private static final String MARKDOWN_CONTENT = loadMarkdownFromJar("org/dromara/assets/config/example.md");

    // 加载 Markdown 文件内容
    private static String loadMarkdownFromJar(String filePath) {
        ClassLoader classLoader = InfoController.class.getClassLoader();
        try (InputStream inputStream = classLoader.getResourceAsStream(filePath)) {
            if (inputStream == null) {
                throw new IllegalArgumentException("无法找到资源文件：" + filePath);
            }
            Scanner scanner = new Scanner(inputStream, StandardCharsets.UTF_8.name()).useDelimiter("\\A");
            return scanner.hasNext() ? scanner.next() : "";
        } catch (Exception e) {
            throw new RuntimeException("读取资源文件失败：" + filePath, e);
        }
    }

    // 获取问题页面
    @GetMapping("/hB197MPUDlTrVbnpeiARH6JSo8KEdxvzjumwOtY4WIGacyNCQ5XfFsZgqk30L2")
    public ResponseEntity<String> getQuestion() {
        String htmlContent = "<!DOCTYPE html>" +
            "<html lang=\"en\">" +
            "<head>" +
            "    <meta charset=\"UTF-8\">" +
            "    <title>回答问题</title>" +
            "</head>" +
            "<body>" +
            "    <h2>请回答以下问题：</h2>" +
            "    <p>" + QUESTION + "</p>" +
            "    <form action=\"/markdown/info/validate\" method=\"post\">" +
            "        <input type=\"text\" name=\"answer\" placeholder=\"请输入答案\" required />" +
            "        <button type=\"submit\">提交</button>" +
            "    </form>" +
            "</body>" +
            "</html>";
        return new ResponseEntity<>(htmlContent,
            new HttpHeaders() {{
                setContentType(org.springframework.http.MediaType.TEXT_HTML);
            }},
            HttpStatus.OK);
    }

    // 验证答案并返回 Markdown 转换结果
    @PostMapping("/validate")
    public ResponseEntity<String> validateAnswer(@RequestParam String answer) {
        String htmlContent;
        if (ANSWER.equals(DigestUtil.md5Hex(answer))) {
            htmlContent = markdownToHtml(MARKDOWN_CONTENT);
        } else {
            htmlContent = "<!DOCTYPE html>" +
                "<html lang=\"en\">" +
                "<head>" +
                "    <meta charset=\"UTF-8\">" +
                "    <title>答案错误</title>" +
                "</head>" +
                "<body>" +
                "    <h2>答案错误，请重新尝试！</h2>" +
                "    <a href=\"/markdown/question\">返回问题页面</a>" +
                "</body>" +
                "</html>";
        }
        return new ResponseEntity<>(htmlContent,
            new HttpHeaders() {{
                setContentType(org.springframework.http.MediaType.TEXT_HTML);
            }},
            HttpStatus.OK);
    }

    // 将 Markdown 转换为 HTML
    private String markdownToHtml(String markdown) {
        // 创建解析器和渲染器
        Parser parser = Parser.builder().build();
        HtmlRenderer renderer = HtmlRenderer.builder().build();
        // 将 Markdown 转换为 HTML
        return "<!DOCTYPE html>" +
            "<html lang=\"en\">" +
            "<head>" +
            "    <meta charset=\"UTF-8\">" +
            "    <title>Markdown 转换结果</title>" +
            "</head>" +
            "<body>" +
            "    <h1>以下是 Markdown 转换后的 HTML 内容：</h1>" +
            "    <div>" + renderer.render(parser.parse(markdown)) + "</div>" +
            "</body>" +
            "</html>";
    }
}
